//
//  StockHomeViewController.m
//  RedManStock
//
//  Created by lanou3g on 15/7/26.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "StockHomeViewController.h"
#import "UIDefine.h"
#import "Analyst.h"
#import "Information.h"
#import "InformationTableViewCell.h"
#import "StockAnalystTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "AnalystArticleViewController.h"
#import "AnalystHomeViewController.h"
#import "StockMoreDataTableViewController.h"
#import "StockLineViewController.h"
#import "StockSimpleLineViewController.h"
#import "ParameterHeader.h"
@interface StockHomeViewController ()

@property (nonatomic,retain) NSMutableArray *analystArray;
@property (nonatomic,retain) NSMutableArray *informationArray;
@property (nonatomic,retain) NSMutableArray *noticeArray;

@property (nonatomic,retain) StockLineViewController *stockLineVC;
@property (nonatomic,retain) StockSimpleLineViewController *stockSimpleLineVC;

@end

//三个类型的cell，三个数据源，但后两个存的是同一种模型，即information

@implementation StockHomeViewController
@synthesize stock;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //初始化
    self.analystArray=[NSMutableArray array];
    self.informationArray=[NSMutableArray array];
    self.noticeArray=[NSMutableArray array];
    self.stock=[[Stock alloc]init];
    
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"InformationTableViewCell" bundle:nil] forCellReuseIdentifier:@"information"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"StockAnalystTableViewCell" bundle:nil] forCellReuseIdentifier:@"StockAnalystTableViewCell"];
    
    //设置导航栏右barButtonItem
    UIBarButtonItem *refreshBBI=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(loadNewData)];
    self.navigationItem.rightBarButtonItem=refreshBBI;
    
    //最上方的信息View
    self.tableView.tableHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 420)];
    NSArray* nibView =  [[NSBundle mainBundle] loadNibNamed:@"StockDetailHeadView" owner:self options:nil];
    self.stockDetailHeadView=[nibView objectAtIndex:0];
    self.stockDetailHeadView.frame=CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 200);
    self.stockDetailHeadView.backgroundColor=MyGrayColor;
    self.stockDetailHeadView.openLabel.text=@"";
    [self.tableView.tableHeaderView addSubview:self.stockDetailHeadView];
    
    [self loadNewData];
    
    //加入小K线图构成的子控制器，并把其根视图加在headView上
    self.stockSimpleLineVC=[[StockSimpleLineViewController alloc]init];
    self.stockSimpleLineVC.code=self.stockCode;
    self.stockSimpleLineVC.view.frame=CGRectMake(0, 200, self.view.bounds.size.width, 220);
    [self addChildViewController:self.stockSimpleLineVC];
    [self.view addSubview:self.stockSimpleLineVC.view];
}

//http://api.gongniucaijing.com/stock/info?code=603308&idfa=7B7C9B42-5C18-4EEB-A0F8-6708DE081AAE&machine=iPhone%205&os=iPhone%20OS%208.2&platform=1&protocolVersion=1.0&qudao=0000001&resolution=640%2A1136&token=d58f02522dac7e698a4600c8b18ff02c0b9fa6df&uuid=BULLSTOCK-79460017-C3E5-45EC-B98C-1DD541A61127&version=1.9.0&versionCode=190


- (void)loadNewData{
    
#pragma mark 股票基本信息
    NSString *url=@"http://api.gongniucaijing.com/stock/info";
    [[MyHandle new] requestDataWithURLStr:url parameterBlock:^NSDictionary *{
        
        NSDictionary *dic=@{@"code":self.stockCode};
        return dic;
    } successBlock:^(NSDictionary *responseDic) {
        NSDictionary *dic=[responseDic objectForKey:@"data"];
        
        stock.name=self.stockName;
        stock.code=self.stockCode;
        
        stock.updown=[NSString stringWithFormat:@"%.2f",[[dic objectForKey:@"updown"] floatValue]];
        CGFloat updownRateF=[[dic objectForKey:@"updownRate"] floatValue]*100;
        stock.updownRate=[NSString stringWithFormat:@"%.2f%%",updownRateF];
        stock.nowPrice=[NSString stringWithFormat:@"%.2f",[[dic objectForKey:@"nowPrice"] floatValue]];
        stock.high=[NSString stringWithFormat:@"%.2f",[[dic objectForKey:@"high"] floatValue]];
        stock.low=[NSString stringWithFormat:@"%.2f",[[dic objectForKey:@"low"] floatValue]];
        stock.open=[NSString stringWithFormat:@"%.2f",[[dic objectForKey:@"open"] floatValue]];
        stock.close=[NSString stringWithFormat:@"%.2f",[[dic objectForKey:@"close"] floatValue]];
        CGFloat volumef=[[dic objectForKey:@"volume"] floatValue]/1000000;
        stock.volume=[NSString stringWithFormat:@"%.2f万手",volumef];
        CGFloat turnoverRatef=[[dic objectForKey:@"turnoverRate"] floatValue];
        stock.turnoverRate=[NSString stringWithFormat:@"%.2f%%",turnoverRatef];
        NSString *recommendStr=[[dic objectForKey:@"recommend"] stringValue];
        stock.recommend=[NSString stringWithFormat:@"近期%@人推荐",recommendStr];
        stock.stock_status=[[dic objectForKey:@"stock_status"] stringValue];
        stock.status=[[dic objectForKey:@"status"] stringValue];
        
        NSDate *nd=[NSDate dateWithTimeIntervalSince1970:(float)[[dic objectForKey:@"statusTime"] floatValue]];
        NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"MM-dd HH:mm:ss"];
        NSString *dateStr=[dateFormatter stringFromDate:nd];
        stock.statusTime=dateStr;
        
        //为headView上的视图补全信息
        [self setDataToHeadInfoView];
    } errorBlock:^(NSError *error) {
        [MyHandle setUpMBProgressWithView:self.view Text:@"网络错误，请检查网络"];
    }];
    
#pragma mark - 相关观点,资讯,公告 -
//    http://api.gongniucaijing.com/stock/listall?code=600369&command=0&idfa=7B7C9B42-5C18-4EEB-A0F8-6708DE081AAE&machine=iPhone%205&number=5&offset=0&os=iPhone%20OS%208.2&platform=1&protocolVersion=1.0&qudao=0000001&resolution=640%2A1136&token=d58f02522dac7e698a4600c8b18ff02c0b9fa6df&uuid=BULLSTOCK-79460017-C3E5-45EC-B98C-1DD541A61127&version=1.9.0&versionCode=190
    NSString *url1=@"http://api.gongniucaijing.com/stock/listall";
    [[MyHandle new] requestDataWithURLStr:url1 parameterBlock:^NSDictionary *{
        NSDictionary *dic=@{@"code":self.stockCode,
                            @"command":@"0",
                            @"number":@"5",
                            @"offset":@"0"};
        return dic;
    } successBlock:^(NSDictionary *responseDic) {
        NSDictionary *bigDic=[responseDic objectForKey:@"data"];
        
        //分析师和观点
        
        NSArray *array1=[[bigDic objectForKey:@"viewpoint"] objectForKey:@"lists"];
        NSMutableArray *tempArray1=[NSMutableArray array];
        for (NSDictionary *dic in array1) {
            
            Analyst *analyst=[[Analyst alloc]init];
            analyst.viewPointSB=[[AnalystViewPoints alloc]init];
            [analyst setValuesForKeysWithDictionary:[dic objectForKey:@"analyst"]];
            [analyst.viewPointSB setValuesForKeysWithDictionary:[dic objectForKey:@"viewpoint"]];
            [tempArray1 addObject:analyst];
        }
        self.analystArray=tempArray1;
        
        //资讯
        NSArray *array2=[[bigDic objectForKey:@"news"] objectForKey:@"lists"];
        NSMutableArray *tempArray2=[NSMutableArray array];
        for (NSDictionary *dic in array2) {
            Information *information=[[Information alloc]init];
            [information setValuesForKeysWithDictionary:dic];
            [tempArray2 addObject:information];
        }
        self.informationArray=tempArray2;
        
        //公告
        NSArray *array3=[[bigDic objectForKey:@"announcement"] objectForKey:@"lists"];
        NSMutableArray *tempArray3=[NSMutableArray array];
        for (NSDictionary *dic in array3) {
            Information *information=[[Information alloc]init];
            [information setValuesForKeysWithDictionary:dic];
            [tempArray3 addObject:information];
        }
        self.noticeArray=tempArray3;
        
        //刷新视图
        [self.tableView reloadData];
        
    } errorBlock:^(NSError *error) {
    }];
    
}

//为headView上的股票详情赋值
- (void)setDataToHeadInfoView{
    self.stockDetailHeadView.openLabel.text=self.stock.open;
    self.stockDetailHeadView.closeLabel.text=self.stock.close;
    self.stockDetailHeadView.highLabel.text=self.stock.high;
    self.stockDetailHeadView.lowLabel.text=self.stock.low;
    self.stockDetailHeadView.volumeLabel.text=self.stock.volume;
    self.stockDetailHeadView.recommendLabel.text=self.stock.recommend;
    self.stockDetailHeadView.nowPriceLabel.text=self.stock.nowPrice;
    self.stockDetailHeadView.updownLabel.text=self.stock.updown;
    self.stockDetailHeadView.updownRateLabel.text=self.stock.updownRate;
    
    //股票上升，为红色；股票下降，为绿色
    if ([self.stock.updown floatValue]>=0) {
        self.stockDetailHeadView.backgroundColor=MyRedColor;
    }
    else{
        self.stockDetailHeadView.backgroundColor=MyGreenColor;
    }
    
    //设置导航栏
    self.navigationItem.titleView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 150, 30)];
    UILabel *label1=[UILabel labelWithFrame:CGRectMake(0, 0, 150, 20) text:[NSString stringWithFormat:@"%@(%@)",self.stockName,self.stockCode]];
    label1.font=[UIFont systemFontOfSize:14];
    label1.textAlignment=NSTextAlignmentCenter;
    UILabel *label2=[UILabel labelWithFrame:CGRectMake(0, 20, 150, 10) text:self.stock.statusTime];
    label2.font=[UIFont systemFontOfSize:11];
    label2.textAlignment=NSTextAlignmentCenter;
    label1.textColor=[UIColor whiteColor];
    label2.textColor=[UIColor whiteColor];
    [self.navigationItem.titleView addSubview:label1];
    [self.navigationItem.titleView addSubview:label2];
    
    //加手势
    UITapGestureRecognizer *tapGresture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(moreStockData)];
    [self.stockDetailHeadView addGestureRecognizer:tapGresture];
    
    //去掉下方多余的线
    UIView *view=[[UIView alloc]initWithFrame:CGRectZero];
    self.tableView.tableFooterView=view;
}

//更多股票指标
- (void)moreStockData{
    //跳转到另外一个控制器
    StockMoreDataTableViewController *stockMoreVC=[[StockMoreDataTableViewController alloc]init];
    stockMoreVC.stock=self.stock;
    [self.navigationController pushViewController:stockMoreVC animated:YES];
    
//    StockSimpleLineViewController *stockLineVC=[[StockSimpleLineViewController alloc]init];
//    stockLineVC.code=self.stockCode;
//    stockLineVC.view.backgroundColor=[UIColor blackColor];
//    [self presentViewController:stockLineVC animated:YES completion:nil];
    
}

//跳转到大的K线图,本来想写在下面，后来加到小k线图里面的button上了
//- (void)bigKlineGraphic{
////    StockLineViewController *stockLineVC=[[StockLineViewController alloc]init];
////    stockLineVC.code=self.stockCode;
////    stockLineVC.view.backgroundColor=[UIColor blackColor];
////    [self presentViewController:stockLineVC animated:YES completion:nil];
//    
//    self.stockLineVC.view.backgroundColor=[UIColor blackColor];
//    [self presentViewController:_stockLineVC animated:YES completion:nil];
//    
//}

//分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    int i=0;
    if (self.analystArray.count>0) {
        i++;
    }
    if (self.informationArray.count>0) {
        i++;
    }
    if (self.noticeArray.count>0) {
        i++;
    }
    return i;
}

//区头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}

//区头View
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UILabel *label=[UILabel labelWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 20) text:@""];
    label.textAlignment=NSTextAlignmentCenter;
    label.backgroundColor=[UIColor grayColor];
    if (section==0) {
        label.text=@"荐股理由";
    }
    else if(section==1){
        label.text=@"相关资讯";
    }
    else{
        label.text=@"公告";
    }
    return label;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return 95;
    }
    else{
        return 65;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return self.analystArray.count;
    }
    else if(section==1){
        return self.informationArray.count;
    }
    else{
        return self.noticeArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        StockAnalystTableViewCell *stockAnalystCell=[self.tableView dequeueReusableCellWithIdentifier:@"StockAnalystTableViewCell" forIndexPath:indexPath];
        
        Analyst *analyst=self.analystArray[indexPath.row];
        stockAnalystCell.analyst=analyst;
        if (analyst.avatarImage==nil) {
            
            [stockAnalystCell.avatarImageView sd_setImageWithURL:[NSURL URLWithString:analyst.avatar] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                [stockAnalystCell.avatorButton setBackgroundImage:image forState:UIControlStateNormal];
                analyst.avatarImage=image;
                stockAnalystCell.avatorButton.tag=2000+indexPath.row;
                [stockAnalystCell.avatorButton addTarget:self action:@selector(ClickAnalystAvatar:) forControlEvents:UIControlEventTouchUpInside];
            }];
        }
        
        stockAnalystCell.avatorButton.userInteractionEnabled=YES;
        stockAnalystCell.moreButton.userInteractionEnabled=NO;
        [stockAnalystCell.avatorButton setBackgroundImage:analyst.avatarImage forState:UIControlStateNormal];
        return stockAnalystCell;
        
    }
    else if(indexPath.section==1){
        InformationTableViewCell *informationCell=[self.tableView dequeueReusableCellWithIdentifier:@"information" forIndexPath:indexPath];
        
        Information *information=self.informationArray[indexPath.row];
        informationCell.titleLabel.text=information.title;
        informationCell.titleLabel.numberOfLines=1;
        informationCell.dateLabel.text=information.dateSB;
        informationCell.sourceLabel.text=information.source;
        return informationCell;
        
    }
    else{
        InformationTableViewCell *noticeCell=[self.tableView dequeueReusableCellWithIdentifier:@"information" forIndexPath:indexPath];
        Information *notice=self.noticeArray[indexPath.row];
        noticeCell.titleLabel.text=notice.title;
        noticeCell.titleLabel.numberOfLines=1;
        noticeCell.dateLabel.text=notice.dateSB;
        noticeCell.sourceLabel.hidden=YES;
        return noticeCell;
    }
}

//点击分析师头像，进入分析师详情页
- (void)ClickAnalystAvatar:(UIButton *)button{
    AnalystHomeViewController *analystHomeVC=[[AnalystHomeViewController alloc]initWithHeader:YES footer:YES];
    
    NSInteger index=button.tag-2000;
    analystHomeVC.analyst=self.analystArray[index];
    //    UINavigationController *nVC=[[UINavigationController alloc]initWithRootViewController:analystHomeVC];
    [self.navigationController pushViewController:analystHomeVC animated:YES];
    
}

//选中的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AnalystArticleViewController *webVC=[[AnalystArticleViewController alloc]init];
    
    if (indexPath.section==0) {
        Analyst *analyst=self.analystArray[indexPath.row];
        webVC.webUrl=analyst.viewPointSB.url;
    }
    else if(indexPath.section==1){
        Information *information=self.informationArray[indexPath.row];
        webVC.webUrl=information.url;
    }
    else{
        Information *notice=self.noticeArray[indexPath.row];
        webVC.webUrl=notice.url;
    }
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
